<template>
	<picker class="flex-1"  @change="bindPickerChange" @columnchange="columnchange" :range="array" range-key="name" :value="value" mode="multiSelector">
		<slot></slot>
	</picker>
</template>

<script setup>
	import { ref, unref, getCurrentInstance, nextTick } from "vue";
	import AllAddress from './data.js';
	
	const emit = defineEmits(['change']);
	
	const selectVal = ref(['','','']);
	
	const value = ref([0,0,0]);
	const array = ref([]);
	const index = ref(0);
	
	const { ctx } = getCurrentInstance();
	
	const initSelect = async() => {
		updateSourceDate() // 更新源数据
		await nextTick();
		updateAddressDate() // 更新结果数据
		await nextTick();
		ctx.$forceUpdate()
	}
	
	const columnchange = async d => {
		updateSelectIndex(d.detail.column, d.detail.value) // 更新选择索引
		await nextTick();
		updateSourceDate() // 更新源数据
		await nextTick();
		updateAddressDate() // 更新结果数据
		await nextTick();
		ctx.$forceUpdate()
	}
	
	const updateSourceDate = () => {
		array.value = []
		array.value[0] = AllAddress.map(obj => {
			return {
				name: obj.provinceName
			}
		})
		array.value[1] = AllAddress[unref(value)[0]].city.map(obj => {
			return {
				name: obj.cityName
			}
		})
		array.value[2] = AllAddress[unref(value)[0]].city[unref(value)[1]].county.map(obj => { 
			return {
				name: obj.countyName
			}
		})
	}
	
	const updateSelectIndex = (column, values) => {
		let arr = JSON.parse(JSON.stringify(unref(value)))
		arr[column] = values
		if(column === 0 ) {
			arr[1] = 0
			arr[2] = 0
		}
		if(column === 1 ) {
			arr[2] = 0
		}
		value.value = arr
	}
	
	const updateAddressDate = () => {
		selectVal.value[0] = unref(array)[0][unref(value)[0]].name
		selectVal.value[1] = unref(array)[1][unref(value)[1]].name
		selectVal.value[2] = unref(array)[2][unref(value)[2]].name
	}
	
	const bindPickerChange = e => {
		emit('change', {
			index: unref(value),
			data: unref(selectVal)
		})
	}
	
	initSelect();
</script>

<style>
</style>
